#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<vector>
#include<sys/types.h>
#include<sys/wait.h>

//int main()
//{
//  pid_t id = fork();
//  if(id == 0)
//  {
//    //子进程
//    int cnt = 0;
//    while(cnt < 5)
//    {
//      printf("我是一个子进程，pid：%d, ppid: %d, cnt: %d.\n", getpid(), getppid(), cnt);
//      cnt++;
//      sleep(1);
//    }
//    exit(-1);
//  }
//  else if(id < 0)
//  {
//    exit(1);//无实际含义，仅是测试代码
//  }
//  else
//  {
//    //父进程
//    int statics;
//    pid_t ret = wait(&statics);
//    if(ret == -1)
//    {
//      perror("wait:");
//      exit(-1);
//    }
//    else if((statics & 0xFF) == 0)
//    
//    {
//
//    printf("我是父进程！pid: %d, 子进程退出码为: %d.\n", getpid(), (statics >> 8) & 0xFF);//正常退出   
//    
//    }
//    else 
//    {
//      printf("我是父进程！pid: %d, 子程序异常退出，收到的信号为：%d.\n", getpid(), statics & 0x7F);
//    }
//    
//  
//
//  }
//
//  return 0;
//  }

#define NUM 2

typedef void (*type)();
std::vector<type> func_box;

void func1()
{
  printf("This is func1!\n");
}

void func2()
{
  printf("This is func2!\n");
}

void Load()
{
  func_box.push_back(func1);
  func_box.push_back(func2);
}


int main()
{
  id_t id = fork();

  if(id == 0)
  {
    int count = 0;
    while(count++ < 5)
    {
      printf("child process is runninng!  %d\n",count);
      sleep(1);
    }
    exit(-1);
  }
  else
  {

    printf("This is the begin of father process.\n");
    int status;

    //阻塞等待
    //int ret = waitpid(id, &status, 0);
    //id-->wait the process which have the same id as the parameter(参数) "id"; 
    //status-->store the status of the child process's exit 
    //0-->is a optation, choose "0" means when child is running, father do nothing but wait   
    // if(ret)
    // {
    //   printf("child process exit sucessifully!  return status:%d, exit code:%d\n", WIFEXITED(status),WEXITSTATUS(status));
    // }
    
    int quit = 0; 
    while(!quit)
    {
    //非阻塞等待
    int ret = waitpid(-1, &status, WNOHANG);
    //-1--> wait any child process
    //WNOHANG-->choose "WNOHANG" means make the father process do something when the chaild have not done
    if(ret == 0)
    {
      //wait successifully but the child have not exited
      
      printf("The child process is running, do some other things!\n");

      if(func_box.empty())
      {
        Load();
      }

      size_t i = 0;
      for(type iter; iter = func_box[i]; ++i)
      {

        iter();
        sleep(1);
      }
      
    }
    else if(ret > 0)
    {
      //wait successfully and the child have exited
      printf("The child process have exited, return status is:%d, exit code is:%d\n", WIFEXITED(status), WEXITSTATUS(status));
      quit = 1;
    }
    else
    {
      //wait failed
      printf("wait failed!\n");
      quit = 1;
    }
    
    }
  }
  return 0;
}
